package com.lw.leetcode.tree.a;

import com.lw.leetcode.tree.TreeNode;

/**
 * 110. 平衡二叉树
 *
 * @Author liw
 * @Date 2021/4/16 10:02
 * @Version 1.0
 */
public class Balanced {

    public static void main(String[] args) {

        TreeNode a = new TreeNode(1);
        TreeNode b = new TreeNode(2);
        TreeNode c = new TreeNode(2);
        TreeNode d = new TreeNode(2);
        TreeNode e = new TreeNode(2);
        a.left = b;
        b.left = c;
        a.right = d;

        boolean balanced = new Balanced().isBalanced(a);
        System.out.println(balanced);
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int aa = checkBalanced(root);
        return aa != -1;
    }

    private int checkBalanced(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int a = checkBalanced(node.left);
        int b = checkBalanced(node.right);
        if (a < 0 || b < 0 || a - b > 1 || b - a > 1) {
            return -1;
        }
        return Math.max(a, b) + 1;
    }
}
